<?php
/**
 Template Name:data_result
 * @package WordPress
 * @subpackage Default_Theme
 * @author: shiwei
 */

/**
 * 截取字符串（中文算1个长度）
 * @param $str
 * @param $lenth
 * @param $start
 * @return unknown_type
 */
function subString_UTF8($str, $lenth, $start=0){  
	$len = strlen($str);  
	$r = array();  
	$n = 0;  
	$m = 0;  
	for($i = 0; $i < $len; $i++) {  
		$x = substr($str, $i, 1);  
		$a  = base_convert(ord($x), 10, 2);  
		$a = substr('00000000'.$a, -8);  
		if ($n < $start){  
			if (substr($a, 0, 1) == 0) {  
			}elseif (substr($a, 0, 3) == 110) {  
				$i += 1;  
			}elseif (substr($a, 0, 4) == 1110) {  
				$i += 2;  
			}  
			$n++;  
		}else{  
			if (substr($a, 0, 1) == 0) {  
				$r[ ] = substr($str, $i, 1);  
			}elseif (substr($a, 0, 3) == 110) {  
				$r[ ] = substr($str, $i, 2);  
				$i += 1;  
			}elseif (substr($a, 0, 4) == 1110) {  
				$r[ ] = substr($str, $i, 3);  
				$i += 2;  
           	}else{  
            	$r[ ] = '';  
            }  
            if (++$m >= $lenth){  
            	break;  
            }  
       	}  
	}  
    return join('',$r); 
} 
	
	
/**
 * 句子的关键字高亮显示
 * @param $str
 * @param $words
 * @return unknown_type
 */
function highlight_word($str, $words){
	if(is_array($words)) {          
		foreach($words as $k => $word){    
         	$pattern[$k] = '/(?!<[^>]*)'.
				'('.$word.')'.
				'(?![^<]*>)/ui';   
        	$replace[$k] = "<font style='color:red'>\\1</font>"; 
        }    
    } else {    
       	$pattern =  '/(?!<[^>]*)'.
				'('.$word.')'.
				'(?![^<]*>)/ui';
     	$replace = "<font color='red'>\\1</font>";  
    }        
	return preg_replace($pattern,$replace,$str);  
}



//全局参数()；
	$pageSize = 10 ;
	$pageModel= 10 ; //不允许改变的值
	$selfPageLink = "/" ; //自身链接；
	$autoLink = "" ;
	$siteurl = get_bloginfo('template_url');

	
//父类型参数（找出子类型参数）
	$cat = $_POST['cat'] ; 
	if($cat == null || "" == $cat){
		$cat = $_GET['cat'] ;
	}
	//$categories = "" ;
	//$catStr = "" ;
	if($cat != null && "" != $cat){
		$category_id = get_cat_ID($cat);
		//$categories = get_categories ('child_of='.$category_id) ;
		//$categories = $wpdb->get_results("select p.name,p.term_id as  pterm_id ,t.name,t.term_id as term_id ".
		//	" from wp_terms t ,wp_term_taxonomy m , wp_terms p ".
		//	" where t.term_id = m.term_id and p.term_id = m.parent and p.term_id  ='".$category_id."'") ;
		//foreach ($categories as $category) {
		//	$catStr =$catStr."'".$category->term_id."'," ;
		//}
	}
	$fixdiv = $_POST['fixdiv'] ; 
	if($fixdiv == null || "" == $fixdiv){
		$fixdiv = $_GET['fixdiv'] ;
	}
	if($fixdiv == null ){
		$fixdiv = "" ;
	}
//关键字参数
	$keyword = $_POST['keywords'] ;
	if($keyword == null || "" == $keyword ){
		$keyword = $_GET["keywords"]; 
	}
	//$keyword = "赵云" ;
	//将关键字中的多余空格删除
	$keyword = trim($keyword) ;
	$keyword = preg_replace("/\s+/" ," "  ,$keyword) ;
	keywordStat($keyword) ;
//页码参数	
	$paged = $_POST["paged"]; 
	if($paged == null || "" == $paged ){
		$paged = $_GET["paged"]; 
		if($paged == null || "" == $paged ){
			$paged = 0 ;
		}
	}
	$statNum = $pageSize * ($paged) ;

//使用sphinx
	require 'sphinxapi.php';
	//////////调用sphinx来取得数据///////////////
	$cl = new SphinxClient ();
	$cl->SetServer ( 'localhost', 9312);
	$cl->SetConnectTimeout ( 3 );
	//$catArray = array() ;
	//$catArray[0] = $cat ;
	if($category_id != null && "" != $category_id){
		$catArray = array() ;
		$catArray[0] = $category_id ;
		$cl->setFilter("post_category_id",$catArray);
	}
	$cl->SetArrayResult ( true );
	$cl->SetMatchMode ( SPH_MATCH_ANY);
	$cl->SetLimits ( $statNum, $pageSize ,1000);
	$cl->SetFieldWeights(array("post_title"=>1000, "post_content"=>1));
	//$cl->SetSelect("*") ;
	//$cl->SetSortMode ( SPH_SORT_ATTR_ASC, "gamepi" );
	$res = $cl->Query ( $keyword, "*" );
	$opts = array(
 		'before_match' => '<span style="color:red">',
 		'after_match'  => '</span>',
 		'chunk_separator' => '...'//,
		//'limit'=>300
	);
	
	////////调用sphinx来取得数据///////////////

//要显示的post的id集
	$unionSql = "" ;
	foreach($res['matches'] as $postidsArray){
		//$postids .= $postidsArray['id'].",";
		$unionSql = $unionSql." select ".$postidsArray['id']." as postid ,".$postidsArray['weight']." as weight  from dual  union all ";
	}

//查询部分
	$postQue = "" ;
	if(""==$unionSql){
		$postQue =  "select ID,post_title, post_content,post_game_url,post_game_image,post_category_name from wp_posts where 1!=1 " ;
	}else {
		$unionSql = substr($unionSql,0,strlen($unionSql)-11) ;
		$postQue = "select post.ID,post.post_title, post.post_content,post.post_game_url,post.post_game_image,post.post_category_name from wp_posts post, ".
			"(".$unionSql.") temp where  temp.postid = post.ID order by temp.weight desc " ;
	}
	
	$callback = $_GET['callback'];
	
	$myposts = $wpdb->get_results($postQue);
	
	$keyArray = explode(" ",$keyword) ;

	$html = "<div id='list_center'> ";
	$html .= "<span id='soso_result' class='list_centtopspan'>&nbsp;&nbsp;&nbsp;&nbsp;找到".$res['total_found']."个相关游戏     搜索用时:'".$res['time']."'  </span>" ;
	
	foreach($myposts as $mypost){
		$gamePic = $mypost->post_game_image;
		$gameLink =  $mypost->post_game_url;
		$postLink = get_permalink($mypost->ID);
		$postTitle = $mypost->post_title ; 
		$desContent = $mypost->post_content ;
		if($keyword !=null && ""!=$keyword){
			$postTitle = highlight_word($postTitle,$keyArray) ;
			$desContent = highlight_word(subString_UTF8($desContent,150),$keyArray) ;
		}
		$cat_name = $mypost->post_category_name ;
		$cat_title = "" ;
		if($cat_name == 'andriod' ||$cat_name == 'iphone' || $cat_name == 'windows phone' ){
			$cat_title = "游戏平台:";
		}else {
			$cat_title = "类别:";
		}
		$html .= 
			"<div class='list'>".
			"	<span class='list_img'><a href='".$postLink."'>".
			"		<img src='".$gamePic."' width='104' height='79' alt='".$mypost->post_title."' title='".$mypost->post_title."' />".
			"	</a></span>".
			"	<h3 class='list_title'><a href='".$postLink."'>".$postTitle."</a>".
			"	</h3>".
			"	<span class='list_cat'>".$cat_title."<samp>".$cat_name."</samp></span>".
			"	<p class='list_neirong'>".$desContent."</p>".
			"	<span class='list_add'>游戏源地址：<samp>".$gameLink."</samp></span>".
			"</div>";
		
	}
	$html .= "<div id='scroll'>";
	$totalPage = ceil($res['total_found']/$pageSize) ;
	if($totalPage >0){
		$i = 0 ;
		if(intval($paged) > 0 ){	
			$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".(intval($paged)+1).",&#34".$fixdiv."&#34)' ><img src='".$siteurl."/images/next-top.gif' alt='上一页' title='上一页' class='f_l'/></a>" ;	
		}
		if($totalPage<=$pageModel){
			for(;$i<$totalPage;$i++){
				if($i == intval($paged)){
					$html.="<font class='linknone'>".($i +1)."</font>";
				}else{
					$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
				}
			}
		}elseif($totalPage < $pageModel + 3){
			$halfPageModel = intval($pageModel /3)  ;
			if(intval($paged) < $halfPageModel*2){
				for($i=0;$i < $halfPageModel*2+1;$i++){
					if($i == intval($paged)){
						$html.="<font class='linknone'>".($i +1)."</font>";
					}else {
						$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
					}
				}
				$html.="<a class='linkstyle03'>...</a>";
				for($i = $totalPage-($pageModel-$halfPageModel*2 -2);$i<$totalPage;$i++){
					$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
				}
			}elseif(intval($paged) > $halfPageModel - 1) {
				for($i =0 ;$i< $halfPageModel-1;$i++){
					$html .= "<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
				}
				$html.="<a class='linkstyle03'>...</a>";
				for($i=$totalPage-($pageModel-$halfPageModel);$i < $totalPage;$i++){
					if($i == intval($paged)){
						$html.="<font class='linknone'>".($i +1)."</font>";
					}else{
						$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
					}
				}
			}
		}else{
			$halfPageModel = intval($pageModel /2)  ;
			if(intval($paged) < $halfPageModel-1){
				for($i =0 ;$i< $halfPageModel;$i++){
					if($i == intval($paged)){
						$html.="<font class='linknone'>".($i +1)."</font>";
					}else{
						$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
					}
				}
				$html.="<a class='linkstyle03'>...</a>";
				for($i =$totalPage - ($pageModel - $halfPageModel - 1) ;$i< $totalPage ;$i++){
					$html .= "<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
				}
			}elseif(intval($paged) > $totalPage - ($halfPageModel) ) {
				for($i = 0 ;$i< $halfPageModel-1 ;$i++){
					$html .= "<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
				}
				$html.="<a class='linkstyle03'>...</a>";
				for($i = $totalPage - ($pageModel - $halfPageModel) ;$i< $totalPage;$i++){
					if($i == intval($paged)){
						$html.="<font class='linknone'>".($i +1)."</font>";
					}else{
						$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
					}
				}
			}else {
				$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,0,&#34".$fixdiv."&#34)' class='linkstyle03'>1</a>";
				$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,1,&#34".$fixdiv."&#34)' class='linkstyle03'>2</a>";
				$uses = 3 ;
				if($paged > $totalPage/2){
					$uses = 2 ;
					$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,2,&#34".$fixdiv."&#34)' class='linkstyle03'>3</a>";
				}
				$html.="<a class='linkstyle03'>...</a>";
				$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".(intval($paged)-1).",&#34".$fixdiv."&#34)' class='linkstyle03'>".intval($paged)."</a>";
				$html.="<font class='linknone'>".(intval($paged) +1)."</font>";
				$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".(intval($paged)+1).",&#34".$fixdiv."&#34)' class='linkstyle03'>".(intval($paged) +2)."</a>";
				$html.="<a class='linkstyle03'>...</a>";
				for($i = $totalPage - $uses ;$i< $totalPage;$i++){
					$html .= "<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".$i.",&#34".$fixdiv."&#34)' class='linkstyle03'>".($i +1)."</a>";
				}
			}
		}
		
		
		if(intval($paged)<$totalPage-1){
			$html.="<a href='javascript:getResult(&#34".$keyword."&#34,&#34".$cat."&#34,".(intval($paged)+1).",&#34".$fixdiv."&#34)' ><img src='".$siteurl."/images/next-bottom.gif' alt='下一页' title='下一页' class='f_l' /></a>";
		}
	}
	
	$html .= "</div>";
	$html .= "</div>";
	
	$jsonarray = array('html'=>$html,'fixdiv'=>$fixdiv) ;
	$ccc = json_encode($jsonarray);
//	$ccc = substr($ccc, 0 , $ccc.length -1) ;
//	$ccc = $ccc."]}" ;
	echo $callback.'('.$ccc.')' ;
?>